package array;

import java.util.HashMap;
import java.util.Map;

/**
 * You are given a 0-indexed integer array nums. A pair of indices (i, j) is a bad pair if i < j and j - i != nums[j] - nums[i].
 * <p>
 * Return the total number of bad pairs in nums.
 * <p>
 * Example 1:
 * Input: nums = [4,1,3,3]
 * Output: 5
 * Explanation: The pair (0, 1) is a bad pair since 1 - 0 != 1 - 4.
 * The pair (0, 2) is a bad pair since 2 - 0 != 3 - 4, 2 != -1.
 * The pair (0, 3) is a bad pair since 3 - 0 != 3 - 4, 3 != -1.
 * The pair (1, 2) is a bad pair since 2 - 1 != 3 - 1, 1 != 2.
 * The pair (2, 3) is a bad pair since 3 - 2 != 3 - 3, 1 != 0.
 * There are a total of 5 bad pairs, so we return 5.
 * <p>
 * Example 2:
 * Input: nums = [1,2,3,4,5]
 * Output: 0
 * Explanation: There are no bad pairs.
 *
 * @author jishenghuang
 * @version 20250418
 */
public class CountBadPairs_2364 {

    /**
     * Count the number of pairs if i < j && j - i != nums[j] - nums[i]
     *
     * @param nums the given integer array
     * @return the total number of bad pairs
     */
    public static long countBadPairs(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        long res = 0;

        for (int i = 0; i < nums.length; ++i) {
            int key = nums[i] - i;
            res += i - map.getOrDefault(key, 0);
            map.put(key, map.getOrDefault(key, 0) + 1);
        }

        return res;
    }

    public static void main(String[] args) {
        int[] arr = {4, 1, 3, 3};
        System.out.println(countBadPairs(arr));
    }
}
